package com.demo.gulimall.cart.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.*;

/**
 * @author Chen Yuan
 * @create 2023-06-06  15:00
 */
@Configuration
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class) // 将 CacheProperties 相关配置文件注入
public class MyRedisConfig {

	/**
	 * @param cacheProperties 通过参数获取配置文件的配置
	 */
	@Bean
	public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
		RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

		// 修改 Key、Value 的序列化规则
		config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
		config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

		// 将配置文件中的所有配置注入
		CacheProperties.Redis redisProperties = cacheProperties.getRedis();
		if (redisProperties.getTimeToLive() != null) {
			config = config.entryTtl(redisProperties.getTimeToLive());
		}
		if (redisProperties.getKeyPrefix() != null) {
			config = config.prefixKeysWith(redisProperties.getKeyPrefix());
		}
		if (!redisProperties.isCacheNullValues()) {
			config = config.disableCachingNullValues();
		}
		if (!redisProperties.isUseKeyPrefix()) {
			config = config.disableKeyPrefix();
		}

		return config;
	}
}
